# -*- coding: utf-8 -*-
import os
from pyLib.LogManage import MyLog

base_dir = os.path.dirname(os.path.dirname(__file__))
log = MyLog()


class JsonDeal(object):
    @classmethod
    def get_json_data(cls, value_, json_):
        """
        通过json格式提取字符串
        value: json提取字符串
        json_: json串
        return : 提取的值
        """
        type_ = True
        leave = 0
        num = 0
        list_value_ = value_.split(".")
        data_ = json_
        for i in list_value_:
            if leave == 0:
                data_ = json_
            if i.find("[") > 0:
                type_ = True
            else:
                type_ = False
            try:
                if type_:
                    num = str(i).split("[")[1][0:-1]
                    get_value_ = i.split("[")[0]
                    data_ = data_.get(get_value_)[int(num)]
                else:
                    try:
                        data_ = data_.get(i)
                    except AttributeError as e:
                        pass
                leave += 1
            except TypeError as e:
                log.info(e)
                pass
        leave = 0
        type_ = True
        num = 0
        return data_

    @classmethod
    def get_value(cls, json_data_: dict = None, deal_str: str = None):
        """
        通过${}获取需要保存的值 如果有命名则以返回 命名： 值   否则返回  值最后一个字段： 值
        通过{}获取转换结果 conversion 返回 列表  {"conversion": [*args]}
        ex:
         json_data_=  {1: {2: 234}, 3: 345}    deal_str= ${1.2}  ----> {2: 234} or deal_str= num=${1.2}  ---> {num: 234}
         json_data_=  ***********       deal_str= {1,2,3,4} ----> {'conversion': [1,2,3,4]} or deal_str= {"1", "2", "3"} ----> {'conversion': ["1","2","3"]}
        """

        list_all_ = []
        result = {}
        value_dic_ = {}
        try:
            value_list_ = deal_str.split(",")
            for i in value_list_:
                new_i_ = i.replace("{", "").replace("}", "")
                if "$" in new_i_:
                    if "=" in new_i_:  # 键值对保存 要保存的值 和key的列表
                        k_value_ = new_i_.split("=")[0]
                        v_value_ = new_i_.split("=")[1][1:]
                        data_ = cls.get_json_data(value_=v_value_, json_=json_data_)
                        value_dic_.update({k_value_: data_})
                        result.update(value_dic_)
                    else:
                        var = new_i_[1:]
                        s_num_ = len(var.split("."))
                        k_value_none_ = var.split(".")[s_num_ - 1]
                        data_ = cls.get_json_data(value_=var, json_=json_data_)
                        value_dic_.update({k_value_none_: data_})
                        result.update(value_dic_)
                else:
                    if "\'" in new_i_ or "\"" in new_i_ or "‘" in new_i_ or "“" in new_i_:
                        new_i_ = new_i_.replace("\'", "").replace("\"", "").replace("’", "").replace("‘", ""). \
                            replace("“", "").replace("”", "")
                    else:
                        if "." in new_i_:
                            new_i_ = round(float(new_i_), 5)
                        else:
                            if new_i_ == "":
                                return {}
                            else:
                                try:
                                    new_i_ = int(new_i_)
                                except ValueError as e:
                                    pass
                    list_all_.append(new_i_)
                    result.update({"conversion": list_all_})
            return result
        except IndexError as e:
            pass
            # return str(e)

    @classmethod
    def assert_response(cls, response_dict, deal_string, assert_dict):
        """
        response_dict: 请求响应的json内容
        deal_string：提取请求的表达式
        assert_dict：断言提取值的字段
        """
        r = None
        not_in_ = []
        in_ = []
        res = cls.get_value(response_dict, deal_string)
        for r in res.keys():
            if r in assert_dict.keys():
                print(res[r], assert_dict[r])
                try:
                    assert res[r] == assert_dict[r]  # key存在期望结果 比较value
                    in_.append({r: res[r]})  # key存在于期望结果中
                    continue
                except AssertionError as e:  # key存在于期望结果中 比较失败， 结束所有比较
                    return False, res[r], assert_dict[r]
                except Exception as e:
                    return False, res[r], assert_dict[r]
            else:
                not_in_.append({r: res[r]})  # key不存在于期望结果中
                continue
        return True, not_in_, in_


if __name__ == '__main__':
    print(JsonDeal().assert_response({"err_msg":[{"code":"DATA_MAND","field":"10-N","nrf":999, "4545": 000}]}, "${err_msg[0].code},${err_msg[0].nrf},${err_msg[0].455,${err_msg[0].4545}", {"code": "DATA_MAND", "oppo": 999, "4545": 000, "888":888}))